package com.atguigu.gmall.web.controller;

import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.product.client.ProductFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.FileWriter;
import java.io.IOException;

/**
 * @author: atguigu
 * @create: 2023-04-25 15:33
 */
@Controller
public class IndexController {

    @Autowired
    private ProductFeignClient productFeignClient;


    /**
     * 渲染首页
     *
     * @param model
     * @return
     */
    @GetMapping({"", "/", "/index.html"})
    public String indexHtml(Model model) {
        //1.远程调用商品微服务获取首页分类数据
        Result result = productFeignClient.getBaseCategoryList();
        //x.todo 首页其他数据:广告轮播图;推荐商品;热门;最新商品等都应该调用对应服务来获取 如果有这么多接口 采用CompletableFuture并行调用
        model.addAttribute("list", result.getData());
        return "/index/index";
    }


    @Autowired
    private TemplateEngine templateEngine;


    /**
     * 方式二:采用模板引擎将静态页生成为文件
     *
     * @return
     */
    @GetMapping("createIndex")
    @ResponseBody
    public Result createIndex() throws IOException {
        //1.远程获取数据
        Result result = productFeignClient.getBaseCategoryList();
        //2.调用模板引擎生成静态页文件 D:\develop\nginx-1.12.2\html
        //参数1:模板文件位置名称  参数二:上下文对象(封装模板需要参数)  参数3:写文件对象
        Context context = new Context();
        context.setVariable("list", result.getData());
        FileWriter fileWriter = new FileWriter("D:\\develop\\nginx-1.12.2\\html\\index.html");
        templateEngine.process("/index/index", context, fileWriter);
        return Result.ok();
    }
}
